const axios = require('axios');

const BASE_URL = 'http://localhost:3000/api';

let adminToken = '';

// 测试管理员登录
async function testAdminLogin() {
  try {
    const response = await axios.post(`${BASE_URL}/admin/auth/login`, {
      username: 'admin',
      password: '123456'
    });
    
    console.log('=== 管理员登录响应 ===');
    console.log(JSON.stringify(response.data, null, 2));
    
    if (response.data.code === 200) {
      adminToken = response.data.data.token;
      return true;
    }
    return false;
  } catch (error) {
    console.error('登录失败:', error.response?.data || error.message);
    return false;
  }
}

// 测试获取用户列表
async function testGetUsers() {
  try {
    const response = await axios.get(`${BASE_URL}/admin/users`, {
      headers: { Authorization: `Bearer ${adminToken}` },
      params: { page: 1, limit: 10 }
    });
    
    console.log('\n=== 用户列表响应 ===');
    console.log(JSON.stringify(response.data, null, 2));
    
    return true;
  } catch (error) {
    console.log('\n=== 用户列表响应（错误） ===');
    console.log(JSON.stringify(error.response?.data || {message: error.message}, null, 2));
    console.error('详细错误:', error.message);
    if (error.response) {
      console.error('状态码:', error.response.status);
      console.error('响应头:', error.response.headers);
    }
    return false;
  }
}

// 测试获取订单列表
async function testGetOrders() {
  try {
    const response = await axios.get(`${BASE_URL}/admin/orders`, {
      headers: { Authorization: `Bearer ${adminToken}` },
      params: { page: 1, limit: 10 }
    });
    
    console.log('\n=== 订单列表响应 ===');
    console.log(JSON.stringify(response.data, null, 2));
    
    return true;
  } catch (error) {
    console.error('获取订单列表失败:', error.response?.data || error.message);
    return false;
  }
}

// 测试获取订单统计
async function testGetOrderStats() {
  try {
    const response = await axios.get(`${BASE_URL}/admin/stats/orders`, {
      headers: { Authorization: `Bearer ${adminToken}` }
    });
    
    console.log('\n=== 订单统计响应 ===');
    console.log(JSON.stringify(response.data, null, 2));
    
    return true;
  } catch (error) {
    console.error('获取订单统计失败:', error.response?.data || error.message);
    return false;
  }
}

// 运行所有测试
async function runTests() {
  console.log('开始测试后端API...\n');
  
  if (await testAdminLogin()) {
    await testGetUsers();
    await testGetOrders();
    await testGetOrderStats();
  }
  
  console.log('\n测试完成！');
}

runTests();

